package com.bridgeQQ.client.control
{
	import com.bridgeQQ.client.control.connection.bs.BsClient;
	import com.bridgeQQ.client.core.ICommand;
	import com.bridgeQQ.client.core.SimpleCommandFactory;
	import com.bridgeQQ.client.events.CommandEvent;
	import com.bridgeQQ.client.model.BridgeModel;
	import com.bridgeQQ.client.service.Service;
	
	import flash.display.DisplayObjectContainer;
	
	import mx.core.Application;
	
	public class ApplicationController
	{
		private static var instance:ApplicationController;
		
		private var app:DisplayObjectContainer;
		
		private var _service:Service;
		
		private var controllers:Array = [];
		
		public function ApplicationController()
		{
			if(instance != null)
			{
				throw new Error("The instance has been created!");
			}
			instance = this;
		}
		
		public static function get controller():ApplicationController
		{
		    if(instance == null)
		    {
		    	return new ApplicationController();
		    }
		    return instance;	
		}
		
		public final function init(app:DisplayObjectContainer):void
		{
			this.app = app;
			app.addEventListener(CommandEvent.COMMAND_ACTIVATE, onCommand);
		}
		
		public function set service(value:Service):void
		{
			_service = value;
		}
		
		public function get service():Service
		{
			return _service;
		}
				
		private function onCommand(event:CommandEvent):void
		{
			var command:ICommand = SimpleCommandFactory.getCommand(_service, 
			    event.commandName, event.info);
			if(command != null)
			{
				command.execute();
			}
		}
		
		/**
		 * 注册子controller，该controller在ApplicationController下，一个ApplicationController可以有多个
		 * sub controller. 这些sub controller理论上可以用command来实现，但是由于有内部状态需要处理， 或者之间
		 * 的联系 太紧密所以采用sub controller的形式
		 * @param name
		 * @param subController
		 * 
		 */		
		public function registerSubController(name:String, subController:*):void
		{
			controllers[name] = subController;
		}
		
		public final function getSubController(name:String):*
		{
		    var sc:Object = controllers[name];
		    if(sc == null)
		    {
		    	sc = createSubController(name);
		    	registerSubController(name, sc);
		    }
		    return sc;	
		}
		
		protected function createSubController(name:String):Object
		{
			return null;
		}
	
		public function dispose():void
		{
			
		}

	}
}